package com.nova.scenic.projectlibs.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.*;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
//import android.os.SystemProperties;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.View;
//import android.view.ViewRootImpl;
import android.view.WindowManager;

import com.nova.scenic.projectlibs.util.debug.MyLog;


@SuppressLint("ServiceCast")
public class DevicesUtil {

	private static DevicesUtil mInstance;

	public static DevicesUtil getInstance() {
		if (mInstance == null) {
			mInstance = new DevicesUtil();
		}
		return mInstance;
	}

	StatFs dataFileStats = new StatFs("/data");


	public boolean externalMemoryAvailable() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	public void ensureInputMode(View view) {
//		try {
//			ViewRootImpl viewRoot = view.getViewRootImpl();
//			Method method = viewRoot.getClass().getDeclaredMethod("ensureTouchMode", boolean.class);
//			method.setAccessible(true);
//			method.invoke(viewRoot, true);
//		} catch (Exception e) {
//		}
	}
	
	public void sendTouchTap() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				int inputSource = InputDevice.SOURCE_TOUCHSCREEN;
				float x = 0f ;
				float y = 0f ;
				injectMotionEvent(inputSource, MotionEvent.ACTION_DOWN, SystemClock.uptimeMillis(), x, y, 1.0f);
				injectMotionEvent(inputSource, MotionEvent.ACTION_UP, SystemClock.uptimeMillis(), x, y, 0.0f);
			}
		}).start();

//		IWindowManager mWm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
//		try {
//			mWm.setInTouchMode(true);
//		} catch (RemoteException e) {
//			e.printStackTrace();
//		}
		
	}


	
	/**
	 * Builds a MotionEvent and injects it into the event stream.
	 * 
	 * @param inputSource
	 *            the InputDevice.SOURCE_* sending the input event
	 * @param action
	 *            the MotionEvent.ACTION_* for the event
	 * @param when
	 *            the value of SystemClock.uptimeMillis() at which the event
	 *            happened
	 * @param x
	 *            x coordinate of event
	 * @param y
	 *            y coordinate of event
	 * @param pressure
	 *            pressure of event
	 */
	@SuppressLint("NewApi")
	public void injectMotionEvent(int inputSource, int action, long when, float x, float y, float pressure) {
		final float DEFAULT_SIZE = 1.0f;
		final int DEFAULT_META_STATE = 0;
		final float DEFAULT_PRECISION_X = 1.0f;
		final float DEFAULT_PRECISION_Y = 1.0f;
		final int DEFAULT_DEVICE_ID = 0;
		final int DEFAULT_EDGE_FLAGS = 0;
		MotionEvent event = MotionEvent.obtain(when, when, action, x, y, pressure, DEFAULT_SIZE, DEFAULT_META_STATE, DEFAULT_PRECISION_X, DEFAULT_PRECISION_Y, DEFAULT_DEVICE_ID,
				DEFAULT_EDGE_FLAGS);
		event.setSource(inputSource);
		Log.i("Input", "injectMotionEvent: " + event);
		event.recycle();
//		InputManager.getInstance().injectInputEvent(event, InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
	}

	public long getAvailableExternalMemorySize() {
		if (externalMemoryAvailable()) {
			try {
				File path = Environment.getExternalStorageDirectory();
				StatFs stat = new StatFs(path.getPath());
				long blockSize = stat.getBlockSize();
				long availableBlocks = stat.getAvailableBlocks();
				return availableBlocks * blockSize;
			} catch (Exception e) {
				return 0;
			}
		} else {
			return 0;
		}

	}

		public long getTotalExternalMemorySize() {
			if (externalMemoryAvailable()) {
			try {
				File path = Environment.getExternalStorageDirectory();
				StatFs stat = new StatFs(path.getPath());
				long blockSize = stat.getBlockSize();
				long totalBlocks = stat.getBlockCount();
				return totalBlocks * blockSize;
			} catch (Exception e) {
				return 0;
			}
		} else {

			return 0;

		}
	}

	public long getTotalDataMemorySize() {
		File path = Environment.getDataDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long totalBlocks = stat.getBlockCount();
		long allSize = totalBlocks * blockSize;
		return allSize;
	}


	public long getAvailableInternalMemorySize() {
		File path = Environment.getDataDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();
		return availableBlocks * blockSize;

	}

	// public long getDataAvailableStorage(){
	// dataFileStats.restat("/data");
	// long blockSize = dataFileStats.getBlockSize();
	// return dataFileStats.getAvailableBlocks() * blockSize;
	// }
	//
	// public long getDataTotalStorage(){
	// dataFileStats.restat("/data");
	// long blockSize = dataFileStats.getBlockSize();
	// return dataFileStats.getBlockCount() * blockSize;
	// }

	public boolean isSdSizeEnough() {
		long SD_SIZE_THRESHOLD = 256;
		File path = Environment.getExternalStorageDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long availiableBlocks = stat.getAvailableBlocks();
		long availiableSize = blockSize * availiableBlocks / 1024 / 1024; // MB
		return availiableSize >= SD_SIZE_THRESHOLD;
	}

	public List<ApplicationInfo> getAllAppInfo(Context mContext) {
		PackageManager mPm = mContext.getPackageManager();
		List<ApplicationInfo> list = mPm.getInstalledApplications(0);
		return list;
	}

	/**
	 * 获得所有在启动起中看到的应用
	 * 
	 * @return
	 */
	public List<ApplicationInfo> getLaunchedAppInfo(Context mContext) {
		PackageManager mPm = mContext.getPackageManager();
		List<ApplicationInfo> infos = new ArrayList<ApplicationInfo>();
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<ResolveInfo> list = mPm.queryIntentActivities(intent, 0);
		for (ResolveInfo resolveInfo : list) {

			String packageName = resolveInfo.activityInfo.packageName;
			if ("com.lenovo.nebula.settings".equals(packageName) || 
					"com.lenovo.nebula.app".equals(packageName) || 
					"com.lenovo.tv.appstore".equals(packageName) ||
					"com.lenovo.androidbox".equals(packageName) ||
					"com.nova.scenic.projectlibs.settings".equals(packageName)
					
			) {
				continue;
			}

			try {
				ApplicationInfo info = mPm.getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);

				infos.add(info);
			} catch (NameNotFoundException e) {
				MyLog.e("Error " + e);
			}
		}

		return infos;
		// return getAllAppInfo();
	}

	public static boolean isSdCardMounted() {
		return Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED);
	}

	@SuppressLint("NewApi")
	public Point getScreenPoint(Activity context) {
		Point outSize = new Point();
		context.getWindow().getWindowManager().getDefaultDisplay().getSize(outSize);
		return outSize;

	}
	
	public static final int LANGUAGE_EN = 2;
	public static final int LANGUAGE_ZH = 0;
	public static final int LANGUAGE_TW = 1;

	public static final int CONNECTION_TYPE_CMNET = 0;
	public static final int CONNECTION_TYPE_WAP = 1;
	public static final int CONNECTION_TYPE_NO_CONNECT = 2;

	private static final int CONNECTION_TYPE_WIFI = 3;
	/**
	 * 0 中文
	 * 1 台湾
	 * 2 英文
	 * @return
	 */
	public int getCurrentLanguageEnvironment(Context context) {
		Locale locale = context.getResources().getConfiguration().locale;
		String language = locale.getLanguage();
		int mCurrentLanguageState = 0;
		
		if (language.equals("en")) {
			mCurrentLanguageState = LANGUAGE_EN;
		} else if (locale.equals(Locale.SIMPLIFIED_CHINESE)) {
			mCurrentLanguageState = LANGUAGE_ZH;
		} else if (locale.equals(Locale.TAIWAN)) {
			mCurrentLanguageState = LANGUAGE_TW;
		}
		return mCurrentLanguageState;
	}
	
	@SuppressLint("NewApi")
	public String getChineseResouce(Context mContext,int strRes){
		Configuration config = new Configuration();
		config.setLocale(Locale.CHINESE);
		Resources res = new Resources(mContext.getAssets(), new DisplayMetrics(), config);
		return res.getString(strRes);
	}
	


	public static boolean isAppCanMoveToSDcard(ApplicationInfo info) {
		if(info == null){
			return false;
		}
		return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
	}
	
	
	public float dpToPx(Context mContext,float dp){
		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
		manager.getDefaultDisplay().getMetrics(metrics);
		return (dp*(metrics.densityDpi)/160f);
	}
	
//	public Drawable getIconForAPK(Context context,File file)
//    {
//            if(null == context || !file.exists())
//            {
//                    return null;
//            }
//            String path = file.getAbsolutePath();
//            MyLog.p("get icon by path--->" + path);
//            Drawable icon = null;
//            PackageParser packageParser = new PackageParser();
//
//            DisplayMetrics metrics = new DisplayMetrics();
//            metrics.setToDefaults();
//            PackageParser.Package pkg = packageParser
//                            .parsePackage(new File(path), path, metrics, 0);
//            if(null == pkg)
//            {
//            	MyLog.p("unable to get the pakage, pakage is null!");
//                    return null;
//            }
//            ApplicationInfo info = pkg.applicationInfo;
//            AssetManager am = new AssetManager();
//            am.addAssetPath(path);
//            Resources res = context.getResources();
//            Resources re = new Resources(am, res.getDisplayMetrics(),
//                            res.getConfiguration());
//            if(info.icon != 0)
//            {
//                    icon = re.getDrawable(info.icon);
//            }
//            return icon;
//    }
	
	public boolean isContenx2Activity(Context context){
		return context instanceof Activity;
	}
	
	public String getLineSeparator(){
		return System.getProperty("line.separator");
	}


    /**
     * get the sign
     * @param context
     * @return
     */
    public static String getSign(Context context,String packageName) {
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);
        Iterator<PackageInfo> iter = apps.iterator();
        while(iter.hasNext()) {
            PackageInfo packageinfo = iter.next();

//            return packageinfo.signatures[0].toCharsString();
            if (packageinfo.packageName.equals(packageName)) {
                return packageinfo.signatures[0].toCharsString();
            }
        }

        return null;
    }

}
